// pages/cansai/cansai.js
Page({
    // 独立的时间格式化工具函数，仅在当前页面作用域内
    formatTime(time) {
        // 处理可能的时间对象转换
        if (typeof time === 'string') {
            time = new Date(time);
        }
        var d = time.toLocaleDateString().substring(0,10);
        var t = time.toTimeString().substring(0,8);
        return d + " " + t;
    },
    
    // 格式化选手列表时间的方法
    formatXuanshouTime(xuanshouList) {
        // 复制数组避免直接修改原数据
        let formattedList = [...xuanshouList];
        for(let i = 0; i < formattedList.length; i++) {
            if (formattedList[i].time) {
                formattedList[i].time = this.formatTime(formattedList[i].time);
            }
        }
        return formattedList;
    },

    click: function(e) {
        var that = this;
        var database = wx.cloud.database();
        database.collection("tb_item").where({
            matchid: that.data.matchid,
            index: that.data.category + ""
        }).get().then((res) => {
            // 调用独立方法格式化时间，不直接修改原数据
            //const formattedXuanshou = that.formatXuanshouTime(res.data);//注释掉格式化
            that.setData({
                res: formattedXuanshou//改成res
            });
        });
        that.setData({
            isDisabled:false
        })
        for(let i=0;i<that.data.xuanshou.length;i++){
            var time = that.data.xuanshou[i].time;//老师版本的格式化
            var d = time.toLocaleDateString().substring(0,10);
            var t = time.toTimeString().substring(0,8);
            time = d+" "+t;
            that.data.xuanshou[i].time = time;
            //判断当前选手是否已经在到达选手当中
            if(that.data.xuanshou[i].userid == that.data.userid){
                that.setData({
                    isDisabled:true
                })
            }
        }

        this.setData({
            category: e.currentTarget.id + ""
        });
    },

    tijiao() {
        var that = this;
        var matchid = this.data.matchid;
        var index = this.data.category+'';
        var userid = this.data.userid;
        var username = this.data.username;
        var time = new Date();
        var image = null;
        
        wx.chooseMedia({
            count: 1,
            success(res) {
                console.log(res.tempFiles)
                var po = res.tempFiles[0].tempFilePath.lastIndexOf(".")
                var ext = res.tempFiles[0].tempFilePath.slice(po)
                wx.cloud.uploadFile({
                    cloudPath: matchid + index + userid + new Date().getTime() + ext,
                    filePath: res.tempFiles[0].tempFilePath,
                    success(res) {
                        console.log(res.fileID);
                        image = res.fileID;
                        that.setData({
                            currentImage: image
                        });

                        var database = wx.cloud.database();
                        
                    var data ={
                      matchid:matchid,
                      index:index,
                      userid:userid,
                      username:username,
                      time:time,
                      image:image
                    }
                        database.collection("tb_item").add({
                            data: {
                                matchid: matchid,
                                index: index,
                                userid: userid,
                                username: username,
                                time: time,
                                image: image
                            }
                        }).then((s) => {
                            if (s) wx.showToast({
                                title: '提交图片成功',
                            })
                            that.setData({
                                isDisabled:true
                            })
                            var time = data.time;
                            var d = toLocaleDateString().substring(0,10);
                            var t = time.toTimeString().substring(0,8);
                            time = d+" "+t;
                            data.time = time;
                            that.data.xuanshou.push(data);
                            that.setData({
                                xuanshou:that.data.xuanshou
                            })
                        })
                    }
                })
            }
        })
    },
dianji(){
    this.setData({
        dialogShow_match:true
    })
},
    /**
     * 页面的初始数据
     */
    data: {
        dialogShow_match: false,
        matchid: null,
        match: {},
        picnames: [],
        category: 0,
        picurls: [],
        index: 0,
        userid: null,
        username: null,
        xuanshou: [],
        isDisabled:false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        var that = this;
        
        // 获取用户ID
        wx.getStorage({
            key: "userid",
            success(res) {
                that.setData({
                    userid: res.data
                });
                var database = wx.cloud.database();
                database.collection("user").where({
                    _id: that.data.userid
                }).get().then((r) => {
                    if (r.data.length > 0) {
                        that.setData({
                            username: r.data[0].name
                        });
                    }
                })
            }
        });

        // 获取比赛ID
        wx.getStorage({
            key: "matchid",
            success(res) {
                console.log('storage数据:' + res.data);
                that.setData({
                    matchid: res.data
                });
                console.log('match_id:' + that.data.matchid);
                
                var database = wx.cloud.database();
                // 查询比赛信息
                //24.为了让用户一登录页面就可以显示当前场景已经完成比赛的选手的时间和信息，需要在cansai.js的onload中添加如下代码
                database.collection("tb_match").where({
                    _id: that.data.matchid
                }).get().then((res) => {
                    if (res.data.length > 0) {
                        that.setData({
                            match: res.data[0]
                        });
                        
                        // ================= 代码修复开始 =================
                        // 将导航栏标题设置为比赛的名称
                        wx.setNavigationBarTitle({
                           title: res.data[0].title
                        });
                        // ================== 代码修复结束 ==================

                        var picnames = [];
                        var match = that.data.match;
                        var picurls = [];
                        if (match.imageList && match.imageList.length > 0) {
                            for (let i = 0; i < match.imageList.length; i++) {
                                var data = match.imageList[i];
                                picurls.push('' + data);//去除http
                                var loc = data.lastIndexOf("/");
                                data = data.slice(loc + 1);
                                loc = data.lastIndexOf("_");
                                data = data.slice(0, loc);
                                picnames.push(data);
                            }
                            that.setData({
                                picnames: picnames,
                                picurls: picurls
                            });
                        }
                    }
                });

                // 查询参赛选手信息
                database.collection('tb_item').where({
                    matchid: that.data.matchid,
                    index: "0"
                }).get().then((g) => {
                    // 调用独立方法格式化时间
                    const formattedXuanshou = that.formatXuanshouTime(g.data);
                    that.setData({
                        xuanshou: formattedXuanshou
                    });
                });
            }
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
var that = this;
var database = wx.cloud.database();
database.collection('tb_item').where({
    matchid:that.data.matchid,
    index:0+""
}).get().then((g)=>{
    that.setData({
        xuanshou:g.data});
        for(let i=0;i<that.data.xuanshou.length;i++){
            var time = that.data.xuanshou[i].time;
            var d = time.toLocaleDateString().substring(0,10);
            var t = time.toTimeString().substring(0,8);
            time = d+" "+t;
            that.data.xuanshou[i].time = time;

            if(that.data.xuanshou[i].userid == that.data.userid){
              that.setData({
                isDisabled:true
              })
            }
          }
          that.setData({
            xuanshou:that.data.xuanshou
          });
 
        
    
    })
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})